%%% @doc
%%%выдает идентификаторы
%%% @end
-module(id_manager).
-include_lib("definitions.hrl").
%% API
-export([init/0, get_next_id/0, start/0, stop/0]).
%-define(KEY_FOR_LAST_RECORD, 1).
-define(TABLE_ID_PATH, "out\\tableForId.txt").
stop() ->
  io:format("id manager finished~n"),
  %{?DB_NODE, manager} ! stop.
  case whereis(manager) of
    undefined -> ok;
    Pid -> Pid ! stop
  end.

get_next_id() ->
  %{?DB_NODE, manager} ! {next, self()},
  manager ! {next, self()},
  receive
    {nextId, Id} when is_integer(Id)
      -> Id
  end.

start() ->
  io:format("man start~n"),
  register(manager, spawn(id_manager, init, [])).

readTableFile() ->
  case ?DEBUG of
    true ->
      {ok, Tab} = dets:open_file(tableForId, [{type, set}, {file, ?TABLE_ID_PATH},
        {auto_save, infinity}, {ram_file, true}, {keypos, #key_id_dts.key}]),
      Tab;
    false ->
      {ok, Tab} = dets:open_file(?TABLE_ID_PATH),
      Tab
  end.

init() ->
  %io:format("manager init~n"),
  Table = readTableFile(),
  Previous =
    case dets:lookup(Table, ?KEY_FOR_LAST_RECORD)
    of
      [X] -> X;
      [] -> #key_id_dts{}
    end,
  StartIndex = Previous#key_id_dts.value,
  %io:format("manager loop~n"),
  loopEvent(StartIndex, Table)
.

loopEvent(CurrentIndex, FileTable) ->
  receive
    {next, From} -> From ! {nextId, CurrentIndex + 1},
      loopEvent(CurrentIndex + 1, FileTable);
    stop ->
      %положить в файл
      LastId = #key_id_dts{key = ?KEY_FOR_LAST_RECORD, value = CurrentIndex},
      dets:insert(FileTable, LastId),
      %dets:sync(FileTable),
      dets:close(FileTable),
      ok
  end.